
package com.yuanmei.datas;

import android.util.Log;

import com.yuanmei.model.TdxStockInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import io.realm.Realm;
import io.realm.RealmConfiguration;

public class TdxStockInfoRealm {
    private static final String TAG = TdxStockInfoRealm.class.getName();

    public static final String RealmName = "tdx_stock_info.realm";
    private static void importTdxStockInfoJsonFile(Realm realm, String jsonFile) {
        try {
            InputStreamReader ins = new InputStreamReader(
                    new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(ins);
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            ins.close();

            JSONArray tdxStockInfoArray = new JSONArray(builder.toString());

            realm.beginTransaction();
            for (int i = 0; i < tdxStockInfoArray.length(); i++) {
                JSONObject item = tdxStockInfoArray.getJSONObject(i);
                TdxStockInfo quote = new TdxStockInfo(item);
                if (!quote.isValidRecord()) {
                    Log.e(TAG, "Fail to construct stock:" + i);
                    continue;
                }
                realm.insertOrUpdate(quote);
            }
            realm.commitTransaction();
            Log.i(TAG, "Success to import Tdx Stock info");
        } catch (IOException e) {
            Log.e(TAG, "Fail to access Tdx Stock info file:" + jsonFile, e);
        } catch (JSONException e) {
            Log.e(TAG, "Fail to parse Tdx Stock info json file:" + jsonFile, e);
        }
    };

    public static void importTdxStockInfoDbFromJson(String jsonFile) {
        RealmConfiguration tdxStockInfoRealmConfig = new RealmConfiguration.Builder()
                .name(RealmName)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm realm = Realm.getInstance(tdxStockInfoRealmConfig);
        importTdxStockInfoJsonFile(realm, jsonFile);
        realm.close();
        if(!Realm.compactRealm(tdxStockInfoRealmConfig)) {
            Log.w(TAG, "After update tdxStockInfoRealmConfig, compact realm fail");
        }
    }

}
